//
//  DeviceListViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/25.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "DeviceListViewController.h"
#import "DeviceTableViewCell.h"
#import "SearchListViewController.h"
#import "TabBarViewController.h"
#import "GetUserDeviceApi.h"
#import "DeleteDeviceApi.h"
#import "RenameDeviceApi.h"
#import "YYModel.h"
#import "DeviceModel.h"


@interface DeviceListViewController ()<UITableViewDelegate,UITableViewDataSource,MGSwipeTableCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
/** 空数据提示 */
@property (nonatomic,strong) UILabel *emptyLabel;
@property (nonatomic,strong) UIImageView *emptyImageView;
@property (nonatomic,strong) DeviceModel *deviceModel;
/** 连接或断开设备标志 **/
@property(nonatomic,assign) BOOL state;
@end

@implementation DeviceListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[DTCBluetoothManager shareInstance] scanAroundDevice];//自主控制设备扫描操作

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self.tableView.mj_header beginRefreshing];
    [self getDeviceList];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableView) name:DeviceConnectSuccess object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectDevice) name:SearchDeviceList object:nil];

}

- (void)reloadTableView
{
    [self.tableView reloadData];
}

#pragma mark - 点击事件
- (void)onRightButtonClick:(id)sender
{
    SearchListViewController *vc = [[SearchListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 事件处理
- (void)getDeviceList
{
    [SVProgressHUD dismiss];
    
    GetUserDeviceApi *api = [[GetUserDeviceApi alloc]initWithDic:@{@"type":@"1"}];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = [request responseJSONObject];
        if ([dict[@"errcode"] intValue] == 0)
        {
            [self.dataSource removeAllObjects];
            for (NSDictionary *dic in dict[@"data"])
            {
                
                DeviceModel *model = [DeviceModel yy_modelWithDictionary:dic];
                NSLog(@"mac:%@",model.mac);
                [self.dataSource addObject:model];
            }
            
            if (self.dataSource.count == 0)
            {
                self.emptyLabel.hidden = NO;
                self.emptyImageView.hidden = NO;
            } else {
                self.emptyLabel.hidden = YES;
                self.emptyImageView.hidden = YES;
                
            }
        }
        
        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
    } failure:^(YTKBaseRequest * _Nonnull request) {
        [self.tableView.mj_header endRefreshing];
    }];
}


- (void)settingTime
{
    NSDate * nowDate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString * locationString = [dateformatter stringFromDate:nowDate];
    NSString *sendCode = [NSString stringWithFormat:@"FC00%@%@0000000000000000000000",locationString.fromIndex(2),[self getWeekDayFordate:nowDate]];
    NSLog(@"当前时间：%@",sendCode);
    DTCDeviceModel *device = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    NSData *sendData = [NSString convertHexStrToData:sendCode];
    [[DTCBlueToothSendData sharedInstance] sendDataByData:sendData andInfo:device];
    
    NSData *battery = [NSString convertHexStrToData:getBatteryCode];
    [[DTCBlueToothSendData sharedInstance] sendDataByData:battery andInfo:device];
}

//根据时间获取星期几的字符串
- (NSString *)getWeekDayFordate:(NSDate *)data
{
    NSArray *weekday = [NSArray arrayWithObjects: [NSNull null], @"00", @"01", @"02", @"03", @"04", @"05", @"06", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:data];
    
    NSString *weekStr = [weekday objectAtIndex:components.weekday];
    return weekStr;
}
//- (void)connectDeviceWithModel

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(200);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceTableViewCell *cell = [DeviceTableViewCell dequeueReusableWithTableView:tableView];
    DeviceModel *model = self.dataSource[indexPath.row];
    cell.nameLabel.text = model.name;
    DTCDeviceModel *connectModel = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    if ([connectModel.mac isEqualToString:model.mac])
    {
        cell.connectButton.selected = YES;
    }
    else
    {
        cell.connectButton.selected = NO;
    }
    
//    BOOL connect = cell.connectButton.selected;
    
    __weak typeof(self) weakSelf = self;
    cell.connectDeviceBlcok = ^(BOOL isOn){
//        [weakSelf.tableView reloadData];
//        SAVE_OBJECT(model.mac, DEVICEMAC);
//        weakSelf.deviceModel = model;
//        weakSelf.state = isOn;
        
        if ([DTCBluetoothManager shareInstance].scanDeviceList.count > 0)
        {
            [weakSelf connectDevice:model State:isOn];
        }
        else
        {
            [[DTCBluetoothManager shareInstance] scanAroundDevice];//自主控制设备扫描操作
            [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"没有扫描到设备")];
        }

//        [self connectDevice];

    };


    cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"icon_delete"] backgroundColor:[UIColor colorWithHexString:@"F06161"] padding:px1080Width(80)],[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"icon_ren"] backgroundColor:[UIColor colorWithHexString:@"C8C8C8"] padding:px1080Width(80)]];
    cell.delegate = self;
    
    return cell;
}

- (void)connectDevice:(DeviceModel *)device State:(BOOL)state
{
    NSArray *scanArray = [DTCBluetoothManager shareInstance].scanDeviceList;
    if (state) // 已连接
    {
        for (DTCDeviceModel *scan in scanArray)
        {
            if ([scan.mac isEqualToString:device.mac])
            {
                [[DTCBluetoothManager shareInstance] disconnectDevice:scan];
            }
        }
    }
    else // 未连接
    {
       // 先扫描是否有此设备
        BOOL hasMac = NO;
        for (DTCDeviceModel *scan in scanArray)
        {
            if ([scan.mac isEqualToString:device.mac])
            {
                hasMac = YES;
                break;
            }
            else
            {
                hasMac = NO;
            }
        }
        if (!hasMac)
        {
            [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"未能搜索到手环，请确保手环在手机附近～")];
            [self.tableView reloadData];
            return;
        }
        
         // 先断开所有设备的连接
//        for (DTCDeviceModel *scan in scanArray)
//        {
            [[DTCBluetoothManager shareInstance] cancelAllDeviceConnection];
//        }
        
        [[DTCBluetoothManager shareInstance] scanAroundDevice];
        [self.tableView reloadData];
        
        
        for (DTCDeviceModel *scan in [DTCBluetoothManager shareInstance].scanDeviceList)
        {
            if ([scan.mac isEqualToString:device.mac])
            {
                [[DTCBluetoothManager shareInstance] connectDevice:scan];
                [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"正在连接中...")];
                break;
            }
        }
    }
    
//    for (DTCDeviceModel *scan in scanArray)
//    {
//        if ([scan.mac isEqualToString:device.mac])
//        {
////            [[DTCBluetoothManager shareInstance] disconnectDevice:scan];
//            if (state)
//            {
//                [[DTCBluetoothManager shareInstance] disconnectDevice:scan];
////                self.state = NO;
//            }
//            else
//            {
//                [[DTCBluetoothManager shareInstance] connectDevice:scan];
//                [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"正在连接中...")];
//            }
//        }
//        else
//        {
//            [[DTCBluetoothManager shareInstance] connectDevice:scan];
//            [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"正在连接中...")];
//        }
//    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    DTCDeviceModel *connectModel = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    DeviceModel *model = self.dataSource[indexPath.row];
//    if ([connectModel.mac isEqualToString:model.mac])
//    {
        SAVE_OBJECT(model.mac, MAC);
        SAVE_OBJECT(model.device_id, DEVICEID);
        TabBarViewController *vc = [[TabBarViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        [self settingTime];
//    }
//    else
//    {
//        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"设备未连接")];
//    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(BOOL) swipeTableCell:(UITableViewCell *) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    DeviceModel *model = self.dataSource[indexPath.row];
    if (direction == MGSwipeDirectionRightToLeft)
    {
        switch (index) {
            case 0:
            {
                [[AlertViewManager shareManager] initWithTitle:MyNSLocalizedString(@"提示") message:MyNSLocalizedString(@"您确定要删除此设备？") cancleButtonTitle:MyNSLocalizedString(@"取消") OtherButtonsArray:@[MyNSLocalizedString(@"确定")] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                    if (buttonIndex == 1)
                    {
                        DeleteDeviceApi *api = [[DeleteDeviceApi alloc] initWithDic:@{@"id":model.ids}];
                        [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                            NSDictionary *dic = [request responseJSONObject];
                            if ([dic[@"errcode"] intValue] == 0)
                            {
                                [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"删除成功")];
                                [self getDeviceList];
                            }
                            else
                            {
                                [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"]];
                            }
                        } failure:nil];
                    }
                }];
            }
                break;
            case 1:
            {
                [[AlertViewManager shareManager] initWithEditActionTitle:MyNSLocalizedString(@"提示：请输入修改的名称") message:nil cancleButtonTitle:MyNSLocalizedString(@"取消") OtherButtonsArray:@[MyNSLocalizedString(@"确定")] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                    if (buttonIndex == 1)
                    {
                        NSString *string = [alertController.textFields.firstObject.text stringByReplacingOccurrencesOfString:@" " withString:@""];

                        if (string.length == 0)
                        {
                            [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"名字不能为空")];
                            return;
                        }
                        if (string.length > 20)
                        {
                            [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"名字长度不能超过20个")];
                            return;
                        }

                        if ([NSString isContainsTwoEmoji:string] )
                        {
                            [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"名字不能使用表情")];
                            return;
                        }
                        
                        RenameDeviceApi *api = [[RenameDeviceApi alloc] initWithDic:@{@"id":model.ids,@"name":string}];
                        [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                            NSDictionary *dic = [request responseJSONObject];
                            if ([dic[@"errcode"] intValue] == 0)
                            {
                                [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"重命名成功")];
                                [self getDeviceList];
                            }
                            else
                            {
                                [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"]];
                            }
                        } failure:nil];
                        

                        
                    }
                }];

            }
                break;
                
            default:
                break;
        }
        
    }
    
    return YES;
}

-(void) swipeTableCellWillBeginSwiping:(nonnull MGSwipeTableCell *) cell
{
    
}
-(void) swipeTableCellWillEndSwiping:(nonnull MGSwipeTableCell *) cell
{
    
}






#pragma mark - 通知处理

#pragma mark - 初始化
- (void)setNavigationStyle
{
    [self setNavigationBarTitle:MyNSLocalizedString(@"设备列表")];
    [self setRightButtonImage:[UIImage imageNamed:@"nav_icon_add"]];
}

#pragma mark -- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(getDeviceList)];
        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateRefreshing];
        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStatePulling];
        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateWillRefresh];
        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateIdle];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        [superView addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (UILabel *)emptyLabel{
    
    if (!_emptyLabel) {
        _emptyLabel = [[UILabel alloc]init];
        _emptyLabel.text = MyNSLocalizedString(@"还木有设备，快去添加吧！");
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.textAlignment = NSTextAlignmentCenter;
        _emptyLabel.textColor = [UIColor colorWithHexString:@"6F6F6F"];
        [self.view addSubview:_emptyLabel];
    }
    return _emptyLabel;
}

- (UIImageView *)emptyImageView
{
    if(!_emptyImageView)
    {
        UIView *superView = self.view;
        _emptyImageView = [[UIImageView alloc]init];
        _emptyImageView.image = [UIImage imageNamed:@"icon_empty"];
        [superView addSubview:_emptyImageView];
    }
    return _emptyImageView;
}

- (DeviceModel *)deviceModel
{
    if(!_deviceModel)
    {
        _deviceModel = [[DeviceModel alloc]init];
    }
    return _deviceModel;
}

- (void) masLayoutSubview{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).with.offset(64);
        make.left.right.equalTo(superView);
        make.bottom.equalTo(superView);
    }];
    
    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(superView);
        make.top.mas_equalTo(self.emptyImageView.mas_bottom).with.offset(px1920Height(164));
    }];
    
    [self.emptyImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView.mas_top).with.offset(px1920Height(438));
        make.centerX.equalTo(superView);
        //        make.width.height.mas_equalTo(px1080Width(400));
    }];
    
    self.emptyLabel.hidden = YES;
    self.emptyImageView.hidden = YES;
}
@end
